package cc.eddic.examinationsystem.web;

import cc.eddic.examinationsystem.Role;
import cc.eddic.examinationsystem.core.BaseController;
import cc.eddic.examinationsystem.domain.Student;
import cc.eddic.examinationsystem.dto.StudentModel;
import cc.eddic.examinationsystem.repository.StudentRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Controller
@RequestMapping("/student")
public class StudentController  extends BaseController {

    public StudentController(StudentRepository studentRepository, PasswordEncoder passwordEncoder) {
        this.studentRepository = studentRepository;
        this.passwordEncoder = passwordEncoder;
    }

    //login使用 spring-security-login
    /**
     * 登录

    @GetMapping("/login")
    public String login(Model model) {
        log.debug("come login page");
        model.addAttribute("studentModel", StudentModel.builder().build());
        return "login";
    }
     */


    /**
     * 点登录按钮后,校验(1.输入工号的位数 2.数据库里有无输入工号 3.输入密码是否正确)
     * 登录成功,跳转至landing page

    @PostMapping(value = "/loginVerify")
    public String loginVerify(@ModelAttribute StudentModel studentModel, BindingResult bindingResult, Model model) { // @RequestParam("employeeNo") String employeeNo
        if (log.isDebugEnabled()) {
            log.debug("输入的工号{}", studentModel.getEmployeeNo());
            log.debug("输入的密码{}", studentModel.getPassword());
        }

        if (!bindingResult.hasErrors()) {

            Long inputEmployeeNo = studentModel.getEmployeeNo();
            String inputPwd = studentModel.getPassword();

            if (inputEmployeeNo.toString().length() != 10) {
                bindingResult.reject("ERROR", String.format("工号有误，请重新输入"));
                return "login";
            }

            List<Student> studentList = studentRepository.findAll();
            for (Student s : studentList) {
                if (inputEmployeeNo.equals(s.getEmployeeNo())) {

                    //判断输入密码和库中密码是否一样,不一样,提示错误
                    if (!DigestUtils.md5DigestAsHex((inputPwd).getBytes()).equals(s.getPassword())) {
                        bindingResult.reject("ERROR", String.format("密码有误"));
                        return "login";
                    }

                    //TODO 登录成功进入landing page 【landing page暂无，有了换这】
                    return "landingPage";
                }
            }

            bindingResult.reject("ERROR", String.format("工号不存在，请注册"));

        } else {
            //打印错误
            log.debug("!!!!! {}", bindingResult.getFieldError().getDefaultMessage());
        }

        return "login";
    }
     */



    /**
     * 注册
     * 把空的student对象传递到 HTML 网页
     */
    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("studentModel", StudentModel.builder().build());
        return "sign-up";
    }


    /**
     * 校验注册表单的输入
     *
     * @return 注册成功 跳到login页面
     */
    @PostMapping(value = "/save", params = "save")
    public String save(@ModelAttribute StudentModel studentModel, BindingResult bindingResult, Model model, @RequestParam("Password2") String Password2) {
        if (log.isDebugEnabled()) {
            log.debug("从前端form传来的studentModel = {}", studentModel);
            log.debug("Password2:{}", Password2);
        }

        if (!bindingResult.hasErrors()) {

            //student中是否存在该工号,存在，注册失败，返回登录页面
            List<Student> studentList = studentRepository.findAll();
            for (Student s : studentList) {
                if (studentModel.getEmployeeNo().equals(s.getEmployeeNo())) {
                    if (log.isDebugEnabled()) log.debug("该工号已存在，请登录");
                    bindingResult.reject("ERROR", String.format("该工号已存在，请登录"));
                    return "login";
                }
            }
            //不存在可以注册,注册时校验工号位数
            if (studentModel.getEmployeeNo().toString().length() != 10) {
                if (log.isDebugEnabled()) log.debug("工号有误，请重新输入");
                bindingResult.reject("ERROR", String.format("工号有误，请重新输入"));
                return "sign-up";
            }
            //密码确认
            if (!Password2.equals(studentModel.getPassword())) {
                if (log.isDebugEnabled()) log.debug("请确认密码");
                bindingResult.reject("ERROR", String.format("请确认密码"));
                return "sign-up";
            }

            Student student;
//            String pwd = DigestUtils.md5DigestAsHex((studentModel.getPassword()).getBytes());
            String pwd = passwordEncoder.encode(studentModel.getPassword());
            if (log.isDebugEnabled()) log.debug("pwd: {} => {}", studentModel.getPassword(), pwd);
            student = new Student(studentModel.getEmployeeNo(), studentModel.getName(), studentModel.getGender(), studentModel.getEmail(), studentModel.getMobile(), pwd, Role.EXAMINEE);
            if (log.isDebugEnabled()) log.debug("student:{}", student);
            studentRepository.save(student);

        } else {
            if (log.isDebugEnabled()) log.debug("!!!!! {}", bindingResult.getFieldError().getDefaultMessage());
        }

        return "spring-security-login";
    }

    /**
     * 用户管理主界面
     */
    @GetMapping("/user-management")
    public String management(Model model) {
        log.debug("come management page");
        model.addAttribute("studentModels", studentRepository.findAll().stream().map(StudentModel::from).collect(Collectors.toList()));
        return "user-management";
    }


    @GetMapping("/add2")
    public String add2(Model model) {
        model.addAttribute("studentModel", StudentModel.builder().build());
        return "sign-up-by-admin";
    }

    @PostMapping(value = "/save2", params = "save2")
    public String save2(@ModelAttribute StudentModel studentModel, BindingResult bindingResult, Model model, @RequestParam("Password2") String Password2) {
        if (log.isDebugEnabled()) {
            log.debug("从前端form传来的studentModel = {}", studentModel);
            log.debug("Password2:{}", Password2);
        }

        if (!bindingResult.hasErrors()) {

            //student中是否存在该工号,存在，注册失败，返回用户管理
            List<Student> studentList = studentRepository.findAll();
            for (Student s : studentList) {
                if (studentModel.getEmployeeNo().equals(s.getEmployeeNo())) {
                    bindingResult.reject("ERROR", String.format("该工号已存在"));
                    return "sign-up-by-admin";
                }
            }
            //不存在可以注册,注册时校验工号位数
            if (studentModel.getEmployeeNo().toString().length() != 10) {
                if (log.isDebugEnabled()) log.debug("工号有误，请重新输入");
                bindingResult.reject("ERROR", String.format("工号有误，请重新输入"));
                return "sign-up-by-admin";
            }
            //密码确认
            if (!Password2.equals(studentModel.getPassword())) {
                if (log.isDebugEnabled()) log.debug("请确认密码");
                bindingResult.reject("ERROR", String.format("请确认密码"));
                return "sign-up-by-admin";
            }

            Student student;
//            String pwd = DigestUtils.md5DigestAsHex((studentModel.getPassword()).getBytes());
            String pwd = passwordEncoder.encode(studentModel.getPassword());
            if (log.isDebugEnabled()) log.debug("pwd: {} => {}", studentModel.getPassword(), pwd);
            student = new Student(studentModel.getEmployeeNo(), studentModel.getName(), studentModel.getGender(), studentModel.getEmail(), studentModel.getMobile(), pwd, Role.EXAMINEE);
            if (log.isDebugEnabled()) log.debug("student:{}", student);
            studentRepository.save(student);

        } else {
            if (log.isDebugEnabled()) log.debug("!!!!! {}", bindingResult.getFieldError().getDefaultMessage());
        }

        return "redirect:/student/user-management";
    }

    /**
     * 用户管理-删除用户
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") long id, Model model) {
        studentRepository.deleteById(id);
        model.addAttribute("studentModels", studentRepository.findAll());
        model.addAttribute("success", "success");
        return "user-management";
    }

    /**
     * 用户管理-修改用户信息
     */
    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("studentModel", studentRepository.findById(id).map(StudentModel::from).orElse(StudentModel.builder().build()));
        return "user-edit";
    }

    @PostMapping(value = "/saveEdit", params = "saveEdit")
    public String saveEdit(@ModelAttribute @Valid StudentModel studentModel, BindingResult bindingResult, Model model, @RequestParam("Password1") String Password1, @RequestParam("Password2") String Password2) {
        if (log.isDebugEnabled()) log.debug("studentModel = {}", studentModel);

        val optionalStudent = studentRepository.findById(studentModel.getId());
        if (log.isDebugEnabled()) log.debug("optionalStudent:{}", optionalStudent);

        if (!optionalStudent.isPresent()) {
            bindingResult.reject("ERROR", String.format("找不到 Id = %d 的数据", studentModel.getId()));
            return "user-edit";
        }

        if (!bindingResult.hasErrors()) {

            if (studentModel.getEmployeeNo().toString().length() != 10) {
                bindingResult.reject("ERROR", String.format("工号有误，请重新输入"));
                return "user-edit";
            }

            Student student = optionalStudent.get();
            student.setEmployeeNo(studentModel.getEmployeeNo());
            student.setName(studentModel.getName());
            student.setEmail(studentModel.getEmail());
            student.setGender(studentModel.getGender());
            student.setMobile(studentModel.getMobile());

            if (!studentModel.getPassword().equals("")) {
                //!DigestUtils.md5DigestAsHex((studentModel.getPassword()).getBytes()).equals(optionalStudent.get().getPassword())
                if (!passwordEncoder.matches(studentModel.getPassword(),optionalStudent.get().getPassword())) {
                    bindingResult.reject("ERROR", String.format("旧密码输入有误"));
                    return "user-edit";
                }

                if (!Password1.equals(Password2)) {
                    bindingResult.reject("ERROR", String.format("请确认新密码"));
                    return "user-edit";
                }
                student.setPassword(DigestUtils.md5DigestAsHex(Password2.getBytes()));
            }


            if (log.isDebugEnabled()) log.debug("编辑后的 {}", student);

            studentRepository.save(student);

        } else {
            log.debug("!!!!! {}", bindingResult.getFieldError().getDefaultMessage());
        }

        return "redirect:/student/user-management";
    }


    private final StudentRepository studentRepository;

    private final PasswordEncoder passwordEncoder;
}


//向前台传送数据   前端: <td>${studentModel}</td>
//model.addAttribute("studentModel", studentModel);
